package apex;

import org.junit.Test;

import java.lang.reflect.Field;

/*
Field[] getFields()：获取所有public修饰的成员变量
Field getField(String name)：获取指定名称的 public修饰的成员变量
Field[] getDeclaredFields()：获取所有的成员变量，不考虑修饰符
Field getDeclaredField(String name)：获取指定名称的成员变量，不考虑修饰符
 */
public class Demo {
    @Test
    public void test01() throws ClassNotFoundException {
        Class c = Class.forName("apex.Student");

        Field[] fields = c.getFields();
        for(Field field : fields){
            System.out.println(field);
        }
    }

    @Test
    public void test02() throws ClassNotFoundException {
        Class c = Class.forName("apex.Student");

        Field[] fields = c.getDeclaredFields();
        for(Field field : fields){
            System.out.println(field);
        }
    }

    @Test
    public void test03() throws ClassNotFoundException, NoSuchFieldException {
        Class c = Class.forName("apex.Student");

        Field fields = c.getDeclaredField("sex");
        System.out.println(fields);
    }

    @Test
    public void test04() throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException {
        Class c = Class.forName("apex.Student");

        //获取单个私有的成员变量
        Field fields = c.getDeclaredField("sex");
        //获取单个公开的公共的成员变量
        Field name = c.getField("name");
        //暴力反射
        fields.setAccessible(true);

        //新建对象
        Student stu  = (Student) c.newInstance();

        //获取对象的sex属性
        Object o = fields.get(stu);
        Object o1 = name.get(stu);
        System.out.println(o);
        System.out.println(o1);

    }
    @Test
    public void test05() throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException, InstantiationException {
        Class c = Class.forName("apex.Student");

        //获取单个私有的成员变量
        Field fields = c.getDeclaredField("sex");
        //获取单个公开的公共的成员变量
        Field name = c.getField("name");
        //暴力反射
        fields.setAccessible(true);

        //新建对象
        Student stu  = (Student) c.newInstance();

        //获取对象的sex属性
        Object o = fields.get(stu);
        Object o1 = name.get(stu);
        System.out.println(o);
        System.out.println(o1);

        //设置对象的属性值
        fields.set(stu,"女");
        name.set(stu,"lucy");

        //获取对象的sex属性
        o = fields.get(stu);
        o1 = name.get(stu);
        System.out.println(o);
        System.out.println(o1);

    }


}
